'use client';

import type { TMetadata } from '@/types';
import useUser from '@/hooks/useUser';
import LoadPage from '@/app/[locale]/load/load';
import ErrorPage from '@/app/[locale]/error/error';
import type { IPath } from '@/interfaces';
import { useSearchParams } from 'next/navigation';
import { useState } from 'react';
import Image from 'next/image';
import bg from '@/public/static/bg.png';
import Link from 'next/link';
import UsernameRegister from '@/app/[locale]/register/username';
import PhoneRegister from '@/app/[locale]/register/phone';
import EmailRegister from '@/app/[locale]/register/email';
import QqRegister from '@/app/[locale]/register/qq';
import { NavbarPage } from '@/app/[locale]/navbar';
import FooterPage from '@/app/[locale]/footer';
import { useTranslations } from 'use-intl';

export default function RegisterPage({ metadata }: { metadata: TMetadata }) {
  const userQuery = useUser(metadata);

  if (userQuery.data) {
    return (
      <>
        <NavbarPage metadata={metadata} />
        <Register data={userQuery.data} metadata={metadata} />
        <FooterPage metadata={metadata} />
      </>
    );
  }

  if (userQuery.error) {
    return <ErrorPage error={userQuery.error} />;
  }

  return <LoadPage />;
}

const Register = ({ data, metadata }: { data: IPath; metadata: TMetadata }) => {
  const t = useTranslations('RegisterPage');
  const env = metadata.env;
  const urlSearchParams = useSearchParams();
  const registerType = urlSearchParams?.get('type') || 'username';
  const [switchingRegisterMethod, setSwitchingRegisterMethod] = useState({
    username:
      registerType === 'username' ||
      (!data.phoneConfig?.enable &&
        !data.emailConfig?.enable &&
        !data.qqConfig?.enable),
    phone: registerType === 'phone' && data.phoneConfig?.enable,
    email: registerType === 'email' && data.emailConfig?.enable,
    qq: registerType === 'qq' && data.qqConfig?.enable,
  });

  function onClickRegister(name: string) {
    const obj = { ...switchingRegisterMethod } as any;
    for (let objKey in obj) {
      obj[objKey] = false;
    }
    setSwitchingRegisterMethod({ ...obj, [name]: true });
  }

  return (
    <div className="col p-4">
      <div
        className="row mx-0 rounded-5"
        style={{ background: 'var(--bs-body-bg)' }}
      >
        <div className="col col-xl-6 col-lg-5 col-md-4 col-sm px-0 overflow-hidden">
          <Image
            className="object-fit-cover rounded-start-5"
            src={bg}
            alt="bg"
            placeholder="blur"
            blurDataURL={env.APP_BLUR_DATA_URL}
          />
        </div>
        <div className="col col-xl-6 col-lg-7 col-md-8 col-sm-12 position-relative overflow-hidden px-0">
          <div className="position-absolute top-50 start-50 translate-middle card rounded-5 border-0 w-75">
            <div className="card-body">
              <div className="my-5 hstack gap-2 justify-content-end">
                <div className="cursor-default">{t('accountExist')}</div>
                <div>
                  <Link className="btn btn-light" href="/login">
                    {t('startLogin')}
                  </Link>
                </div>
              </div>
              <div className="vstack gap-4">
                <div className="fs-4 text-start fw-bold">
                  {env.APP_NAME ? (
                    <div>
                      {t('welcomeTo')}
                      &nbsp;
                      {env.APP_NAME}
                    </div>
                  ) : (
                    <div>{t('welcome')}</div>
                  )}
                  <div className="mt-3 fs-5 fw-normal">{t('inputInfo')}</div>
                </div>

                {switchingRegisterMethod.username && (
                  <UsernameRegister data={data} metadata={metadata} />
                )}

                {switchingRegisterMethod.phone && data.phoneConfig?.enable && (
                  <PhoneRegister data={data} metadata={metadata} />
                )}

                {switchingRegisterMethod.email && data.emailConfig?.enable && (
                  <EmailRegister data={data} metadata={metadata} />
                )}

                {switchingRegisterMethod.qq && data.qqConfig?.enable && (
                  <QqRegister data={data} metadata={metadata} />
                )}

                {(data.phoneConfig?.enable ||
                  data.emailConfig?.enable ||
                  data.qqConfig?.enable ||
                  data.clientConfig?.ywClientUrls.find(
                    (item) => item.enable && item.url,
                  )) && (
                  <>
                    <div className="d-flex align-items-center user-select-none">
                      <div
                        className="border-bottom"
                        style={{ height: '1px', width: '45%' }}
                      />
                      <div
                        className="text-muted text-center"
                        style={{ width: '10%' }}
                      >
                        OR
                      </div>
                      <div
                        className="border-bottom"
                        style={{ height: '1px', width: '45%' }}
                      />
                    </div>
                    <div className="vstack gap-4">
                      <div className="hstack gap-4">
                        {!switchingRegisterMethod.username && (
                          <button
                            onClick={onClickRegister.bind(this, 'username')}
                            type="button"
                            className="d-flex btn btn-light w-100 justify-content-center"
                          >
                            <i className="bi bi-person me-2"></i>
                            <span>{t('accountRegistration')}</span>
                          </button>
                        )}

                        {!switchingRegisterMethod.phone &&
                          data.phoneConfig?.enable && (
                            <button
                              onClick={onClickRegister.bind(this, 'phone')}
                              type="button"
                              className="d-flex btn btn-light w-100 justify-content-center"
                            >
                              <i className="bi bi-phone me-2"></i>
                              <span>{t('smsRegistration')}</span>
                            </button>
                          )}

                        {!switchingRegisterMethod.email &&
                          data.emailConfig?.enable && (
                            <button
                              onClick={onClickRegister.bind(this, 'email')}
                              type="button"
                              className="d-flex btn btn-light w-100 justify-content-center"
                            >
                              <i className="bi bi-envelope me-2"></i>
                              <span>{t('emailRegistration')}</span>
                            </button>
                          )}
                      </div>

                      <div className="hstack gap-4 justify-content-center">
                        {(data.clientConfig?.ywClientUrls || [])
                          .filter((item) => item.enable && item.url)
                          .map((item) => {
                            return (
                              <a
                                key={item.clientId}
                                style={{ width: 48, height: 48 }}
                                href={item.url}
                                className="btn btn-light rounded-circle position-relative overflow-hidden"
                              >
                                <Image
                                  className="object-fit-contain position-absolute top-50 start-50 translate-middle"
                                  src={item.clientLogo}
                                  alt={item.clientName}
                                  title={item.clientName + t('registration')}
                                  width={40}
                                  height={40}
                                  placeholder="blur"
                                  blurDataURL={env.APP_BLUR_DATA_URL}
                                />
                              </a>
                            );
                          })}

                        {!switchingRegisterMethod.qq &&
                          data.qqConfig?.enable && (
                            <div
                              className="w-100 p-2 hstack justify-content-center gap-4"
                              title={t('thirdPartyLogin')}
                            >
                              <i
                                onClick={onClickRegister.bind(this, 'qq')}
                                className="bi bi-tencent-qq cursor-pointer fs-1"
                              ></i>
                            </div>
                          )}
                      </div>
                    </div>
                  </>
                )}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};
